
from datetime import datetime
from bson import ObjectId

from app.api.tasks_route import TaskStatus
from app.models.task_model import TaskListQueryModel
from ..database import mongodb
from pymongo.results import InsertOneResult


class TaskService:
    def __init__(self) -> None:
        pass

    def get_all_tasks(self, query: TaskListQueryModel) -> list:
        # Placeholder implementation

        res = mongodb.tasks.find({
            "status": {"$in": [query.get_status_enum().value]} if query.get_status_enum() != TaskStatus.ALL else {"$in": [e.value for e in TaskStatus]}
        }).to_list()
        print(f"Fetched tasks from DB: {res}")
        # tasks = list(res)

        # print(f"Fetched tasks from DB: {res}")

        return res

    def delete_task_by_id(self, task_id: int) -> bool:
        # Placeholder implementation
        result = mongodb.tasks.delete_one({"_id": ObjectId(str(task_id))})
        # result = mongodb.tasks.delete_one
        print(f"Deleting task with id: {task_id}")

        if result.deleted_count == 0:
            return False
        return True

    def create_task(self, title: str, description: str) -> bool:
        # Placeholder implementation
        new_task = {
            "title": title,
            "description": description,
            # "status": TaskStatus.DONE.value,
            "status": TaskStatus.PENDING.value,
            "created_at": datetime.now(),
            "updated_at": datetime.now(),
        }

        new_task = mongodb.tasks.insert_one(new_task)

        new_task = mongodb.tasks.find_one({"_id": new_task.inserted_id})

        print(f"Creating task: {new_task}")
        return True

    def update_task(self, task_id: int, update_data: dict) -> dict:
        # Placeholder implementation
        
        finded_task = mongodb.tasks.find_one({"_id": ObjectId(str(task_id))})
        print(f"Found task: {finded_task}")
        
        updated_task = mongodb.tasks.find_one_and_update({"_id": ObjectId(str(task_id))}, {
            "$set": update_data})
        print(f"Updating task: {update_data}")
        return updated_task

    def toggle_task_status(self, task_id: int, status: TaskStatus):

        mongodb.tasks.find_one_and_update({"_id": ObjectId(str(task_id))}, {
                                          "$set": {"status": status.value, "updated_at": datetime.now()}})
        print(f"Toggling status for task id: {task_id} to {status.value}")
        return True
